package com.github.ghsea.framework.job.support;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import com.github.ghsea.framework.job.core.JobServerKey;
import com.google.common.base.Splitter;

public class JobServerKeyTypeHandler implements TypeHandler<JobServerKey> {

	@Override
	public void setParameter(PreparedStatement ps, int i, JobServerKey serverKey, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, serverKey.toString());
	}

	@Override
	public JobServerKey getResult(ResultSet rs, String columnName) throws SQLException {
		String serverKey = rs.getString(columnName);
		return parse(serverKey);
	}

	@Override
	public JobServerKey getResult(ResultSet rs, int columnIndex) throws SQLException {
		String serverKey = rs.getString(columnIndex);
		return parse(serverKey);
	}

	@Override
	public JobServerKey getResult(CallableStatement cs, int columnIndex) throws SQLException {
		String serverKey = cs.getString(columnIndex);
		return parse(serverKey);
	}

	private JobServerKey parse(String serverKeyVal) {
		List<String> ipAndPort = Splitter.on(":").trimResults().splitToList(serverKeyVal);
		return new JobServerKey(ipAndPort.get(0), Integer.valueOf(ipAndPort.get(1)));
	}

}
